package product;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.print.PrinterException;
import java.text.DecimalFormat;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import java.util.Vector;

import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.OrientationRequested;
import javax.swing.ButtonGroup;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JInternalFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumnModel;
import javax.swing.table.TableRowSorter;

import net.sourceforge.jdatepicker.impl.JDatePanelImpl;
import net.sourceforge.jdatepicker.impl.JDatePickerImpl;
import net.sourceforge.jdatepicker.impl.UtilDateModel;

public class SaleList extends JInternalFrame {

	ButtonGroup bg = new ButtonGroup();
	DefaultTableModel model;// JTable에 입력을위해
	Vector<String> col = new Vector<String>();
	DecimalFormat df = new DecimalFormat("###,###,###.##");
	ProductMain pm;
	SaleUpdate saleupdate = null;

	ArrayList<SaleData> aSal;
	HashMap<String, SaleTotal> hSal;
	HashMap<String, StockData> sto;

	// 달력!
	UtilDateModel startModel = new UtilDateModel();
	UtilDateModel endModel = new UtilDateModel();
	JDatePanelImpl startDatePanel = new JDatePanelImpl(startModel);
	JDatePanelImpl endDatePanel = new JDatePanelImpl(endModel);
	JDatePickerImpl datePicker = new JDatePickerImpl(startDatePanel);
	JDatePickerImpl datePicker1 = new JDatePickerImpl(endDatePanel);

	private JPanel panel;
	private JButton btnNewButton;
	private JTextField findStr;
	private JComboBox comboBox;
	private JScrollPane scrollPane;
	private JTable table;
	private JPanel panel_1;
	private JButton btnNewButton_1;
	private JPanel panel_2;
	private JRadioButton rb1 = new JRadioButton("물건별 총 판매량");;
	private JRadioButton rb2 = new JRadioButton("모든 판매기록");
	private JComboBox comDay;
	private JComboBox comMon;
	private JPanel calen;

	/**
	 * Create the frame.
	 */
	public SaleList(ArrayList<SaleData> a, HashMap<String, SaleTotal> h,
			HashMap<String, StockData> s, ProductMain pm) {
		super("SaleList", true, true, true, false);
		this.aSal = a;
		this.hSal = h;
		this.sto = s;
		this.pm = pm;
		col.add("제품코드");
		col.add("제품명");
		col.add("단가");
		col.add("판매량");
		col.add("판매총액");
		col.add("판매일자");
		col.add("판매번호");
		model = new DefaultTableModel(col, 0) {
			public boolean isCellEditable(int rowIndex, int mColIndex) {
				return false;
			}
		};
		setBounds(100, 100, 724, 300);
		getContentPane().add(getPanel(), BorderLayout.NORTH);
		getContentPane().add(getScrollPane(), BorderLayout.CENTER);
		// 테이블 형태지정
		DefaultTableCellRenderer Center = new DefaultTableCellRenderer();
		Center.setHorizontalAlignment(SwingConstants.CENTER);// 가운데 정렬
		DefaultTableCellRenderer Right = new DefaultTableCellRenderer();
		Right.setHorizontalAlignment(SwingConstants.RIGHT);// 우측 정렬
		TableColumnModel tcmSchedule = table.getColumnModel();
		tcmSchedule.getColumn(0).setCellRenderer(Center);
		tcmSchedule.getColumn(1).setCellRenderer(Center);
		tcmSchedule.getColumn(2).setCellRenderer(Right);// 단가
		tcmSchedule.getColumn(3).setCellRenderer(Center);
		tcmSchedule.getColumn(4).setCellRenderer(Right);// 금액
		tcmSchedule.getColumn(5).setCellRenderer(Center);
		tcmSchedule.getColumn(6).setCellRenderer(Center);

		table.getColumn("판매총액").setPreferredWidth(110);
		table.setRowHeight(20); // 테이블 상하폭지정
		table.getTableHeader().setReorderingAllowed(false);
		table.getTableHeader().setResizingAllowed(false);
		table.setRowSorter(new TableRowSorter(model));
	}

	public String replace(String s) {
		String temp = s.replace(",", "");
		String temp2 = temp.replace("원", "");
		return temp2;
	}

	public void setRow(Vector<String> row, String find, SaleData value) {

		row.add(value.getProCode());// 코드
		row.add(value.getProName());// 제품명
		String pstr = df.format((double) value.getProPrice());
		row.add(pstr + "원");// 단가
		row.add(String.valueOf(value.getSaleEa()));// 판매량
		String tstr = df.format((double) value.getProTot());
		row.add(tstr + "원");// 판매총액
		row.add(value.getSaleDate());// 판매일자
		row.add(String.valueOf(value.getSaleCnt()));
		model.addRow(row);

	}

	public void search() {

		if (model.getRowCount() > 0) { // 행의 수
			for (int i = model.getRowCount() - 1; i > -1; i--) {
				model.removeRow(i);// 테이블을 초기화
			}
		}
		String find = findStr.getText();
		if (rb1.isSelected()) {// 총판매량

			Set<String> st = hSal.keySet();
			Iterator<String> it = st.iterator();
			// index번호 순서대로
			while (it.hasNext()) {
				Vector<String> row = new Vector<String>();
				String key = it.next();
				SaleTotal value = hSal.get(key);
				if (comboBox.getSelectedIndex() == 0) {
					if (value.getProName().contains(find)) {
						row.add(value.getProCode());
						row.add(value.getProName());
						String pstr = df.format((double) value.getProPrice());
						row.add(pstr + "원");
						row.add(String.valueOf(value.getSaleEa()));
						String tstr = df.format((double) value.getProTot());
						row.add(tstr + "원");
						model.addRow(row);
					}
				} else if (comboBox.getSelectedIndex() == 1) {
					if (value.getProCode().contains(find)) {
						row.add(value.getProCode());
						row.add(value.getProName());
						String pstr = df.format((double) value.getProPrice());
						row.add(pstr + "원");
						row.add(String.valueOf(value.getSaleEa()));
						String tstr = df.format((double) value.getProTot());
						row.add(tstr + "원");
						model.addRow(row);
					}
				}
			}

		} else if (rb2.isSelected()) {// 모든데이터

			String stTermMonRes = String.valueOf(datePicker.getModel()
					.getMonth() + 1);
			String stTermDayRes = String
					.valueOf(datePicker.getModel().getDay());
			if (stTermMonRes != null && stTermDayRes != null) {
				if (stTermMonRes.length() < 2)
					stTermMonRes = "0" + stTermMonRes;
				if (stTermDayRes.length() < 2)
					stTermDayRes = "0" + stTermDayRes;
			}

			String mon = (String) comMon.getSelectedItem();
			String day = (String) comDay.getSelectedItem();

			for (int i = 0; i < aSal.size(); i++) {
				Vector<String> row = new Vector<String>();
				SaleData value = aSal.get(i);// index번호 순서대로
				int valDate = Integer.parseInt(value.getSaleDate().substring(2,
						6));

				if (mon.equals("월별") && day.equals("일별")) {
					if ((value.getProCode().contains(find) || value
							.getProName().contains(find))) {
						setRow(row, find, value);
					}
				} else {
					int strTem = Integer.parseInt(stTermMonRes + stTermDayRes);
					int endTem = Integer.parseInt(mon + day);
					if ((value.getProCode().contains(find) || value
							.getProName().contains(find))
							&& strTem <= valDate
							&& endTem >= valDate) {
						setRow(row, find, value);
					}
				}
			}
		}
	}

	public void mouseC() {
		int index = table.getSelectedRow();// 선택된 열의 table index번호를 저장
		Vector<String> vec = new Vector<String>();// 벡터생성
		vec.add((String) table.getValueAt(index, 0));
		vec.add((String) table.getValueAt(index, 1));
		vec.add(replace((String) table.getValueAt(index, 2)));
		vec.add((String) table.getValueAt(index, 3));
		vec.add(replace((String) table.getValueAt(index, 4)));
		vec.add((String) table.getValueAt(index, 5));
		vec.add((String) table.getValueAt(index, 6));
		// 자리별 정보를 Vector에 추가

		if ((String) table.getValueAt(index, 5) == null) {
			return;
		}
		if (saleupdate == null) {
			saleupdate = new SaleUpdate(vec, model, aSal, hSal, index, sto);
			saleupdate.setBounds(110, 30, 220, 300);
			pm.contentPane.add(saleupdate);
			saleupdate.setVisible(true);
		} else if (saleupdate != null) {
			saleupdate.setVisible(false);
			saleupdate = null;
			mouseC();
		}

	}

	private JPanel getPanel() {
		if (panel == null) {
			panel = new JPanel();
			panel.setLayout(new BorderLayout(0, 0));
			panel.add(getFindStr(), BorderLayout.CENTER);
			panel.add(getComboBox(), BorderLayout.WEST);
			panel.add(getPanel_1(), BorderLayout.EAST);
			panel.add(getPanel_2(), BorderLayout.NORTH);
		}
		return panel;
	}

	private JButton getBtnNewButton() {
		if (btnNewButton == null) {
			btnNewButton = new JButton("조회");
			btnNewButton.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					search();
				}
			});
		}
		return btnNewButton;
	}

	private JTextField getFindStr() {
		if (findStr == null) {
			findStr = new JTextField();
			findStr.addKeyListener(new KeyAdapter() {
				@Override
				public void keyReleased(KeyEvent e) {
					if (e.getKeyCode() == KeyEvent.VK_ENTER) {
						search();
					}
				}
			});
			findStr.setColumns(10);
		}
		return findStr;
	}

	private JComboBox getComboBox() {
		if (comboBox == null) {

			comboBox = new JComboBox();
			comboBox.setModel(new DefaultComboBoxModel(new String[] { "제품명",
					"제품코드" }));
		}
		return comboBox;
	}

	private JScrollPane getScrollPane() {
		if (scrollPane == null) {
			scrollPane = new JScrollPane();
			scrollPane.setViewportView(getTable());
		}
		return scrollPane;
	}

	private JTable getTable() {
		if (table == null) {
			table = new JTable(model);
			table.addMouseListener(new MouseAdapter() {
				@Override
				public void mouseClicked(MouseEvent arg0) {
					if (rb2.isSelected()) {
						mouseC(); // 마우스 클릭 매서드
					}
				}
			});
		}
		return table;
	}

	private JPanel getPanel_1() {
		if (panel_1 == null) {
			panel_1 = new JPanel();
			panel_1.add(getBtnNewButton());
			panel_1.add(getBtnNewButton_1());
		}
		return panel_1;
	}

	private JButton getBtnNewButton_1() {
		if (btnNewButton_1 == null) {
			btnNewButton_1 = new JButton("인쇄");
			btnNewButton_1.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					try {
						MessageFormat headerFormat = new MessageFormat("프린트테스트"); // 타이틀.
						MessageFormat footerFormat = new MessageFormat(
								"- {0} -"); // 페이지.자동증가된다.
						PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet(); // 프린트설정.(용지를
																							// 가로로
																							// 할지
						// 세로로 할지.)
						aset.add(OrientationRequested.LANDSCAPE); // (용지 디폴트를
																	// 가로로.
						table.print(JTable.PrintMode.FIT_WIDTH, headerFormat,
								footerFormat, true, aset, true); // JTable 붙인다.
					} catch (PrinterException pe) {
						System.err.println("Error printing: " + pe.getMessage());
					}

				}
			});
		}
		return btnNewButton_1;
	}

	private JPanel getPanel_2() {
		if (panel_2 == null) {
			panel_2 = new JPanel();
			bg.add(rb1);
			bg.add(rb2);
			panel_2.add(getCalen());
			panel_2.add(getComMon());
			panel_2.add(getComDay());
			panel_2.add(rb1);
			rb2.setSelected(true);
			panel_2.add(rb2);
		}
		return panel_2;
	}

	private JComboBox getComDay() {
		if (comDay == null) {
			comDay = new JComboBox();
			comDay.setModel(new DefaultComboBoxModel(
					new String[] { "일별", "01", "02", "03", "04", "05", "06",
							"07", "08", "09", "10", "11", "12", "13", "14",
							"15", "16", "17", "18", "19", "20", "21", "22",
							"23", "24", "25", "26", "27", "28", "29", "30",
							"31" }));
		}
		return comDay;
	}

	private JComboBox getComMon() {
		if (comMon == null) {
			comMon = new JComboBox();
			comMon.setModel(new DefaultComboBoxModel(new String[] { "월별", "01",
					"02", "03", "04", "05", "06", "07", "08", "09", "10", "11",
					"12" }));
		}
		return comMon;
	}

	private JPanel getCalen() {
		if (calen == null) {
			calen = new JPanel();
			datePicker.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					String stTermMonRes = String.valueOf(datePicker.getModel()
							.getMonth() + 1);
					String stTermDayRes = String.valueOf(datePicker.getModel()
							.getDay());
					if (stTermMonRes != null && stTermDayRes != null) {
						if (stTermMonRes.length() < 2)
							stTermMonRes = "0" + stTermMonRes;
						if (stTermDayRes.length() < 2)
							stTermDayRes = "0" + stTermDayRes;
					}
					comMon.setSelectedItem(stTermMonRes);
					comDay.setSelectedItem(stTermDayRes);
				}
			});
			calen.add(datePicker);
		}
		return calen;
	}
}